package liuliu.throughwaring.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import net.tsz.afinal.FinalDb;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.control.net.HttpTask;
import liuliu.throughwaring.control.task.addTask;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.InvokeReturn;
import liuliu.throughwaring.ui.activity.NewCompanyListActivity;

/**
 * Created by Administrator on 2016/2/18.
 */
public class NewCompany extends Service {
    FinalDb finalDb;
    private Handler handler = new Handler();

    public class NewCompanyBinder extends Binder {
        public IBinder getCompany() {

            return null;
        }
    }

    addTask add;

    /**
     * 定时提交离线数据
     */
    private void upLoad() {
        add = new addTask(this);
        if (Utils.isNetworkAvailable(this)) {

            List<CompanyModel> unit = finalDb.findAllByWhere(CompanyModel.class, "IsUpLoad='0'");
            if (unit.size() > 0) {
                //未提交数据
                for (CompanyModel model : unit) {
                    add.addCompany(model, null);
                }
            }
        }
    }

    private void getCompanyNew() {
        /*
         * 获取未下载的通知通告
         */
        HttpTask task = new HttpTask(NewCompany.this);
        //检查最后一个消息的时间

        task.start("PushCompany", "", "CompanyModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            System.out.println("新企业信息下载成功");
                            List<CompanyModel> newCompanys = new ArrayList<CompanyModel>();
                            for (int i = 0; i < invokeReturn.getData().size(); i++) {
                                newCompanys.add((CompanyModel) invokeReturn.getData().get(i));
                                CompanyModel companyModel = (CompanyModel) invokeReturn.getData().get(0);
                                List<CompanyModel> cms = finalDb.findAllByWhere(CompanyModel.class, "CompanyId= '" + companyModel.getCompanyId() + "'");
                                if (cms.size() > 0) {

                                } else {
                                    finalDb.save(companyModel);
                                }

                            }
                            if (invokeReturn.getData().size() > 0) {
                                showNEW(newCompanys);
                                //显示提示信息
                            }
                        } else {
                            //错误提示信息
                            System.out.println("新企业信息:" + invokeReturn.getMessage());
                        }
                    }
                } else {
                    System.out.println("新企业信息下载失败");
                }
            }
        });
    }


    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Message msg = handler.obtainMessage();
            msg.obj = 0;
            handler.sendMessage(msg);
            handler.postDelayed(this, 60000);
        }
    };

    private void showNEW(List<CompanyModel> list) {
        //定义NotificationManager
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        //定义通知栏展现的内容信息
        int icon = R.mipmap.icon;
        CharSequence tickerText = "我的通知栏标题";
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);

        //定义下拉通知栏时要展现的内容信息
        Context context = getApplicationContext();
        CharSequence contentTitle = "新企业信息";
        CharSequence contentText = "需要录入人员信息的企业信息,共" + list.size() + "条";
        Intent notificationIntent = new Intent(this, NewCompanyListActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("newCompanyModels", (Serializable) list);
        notificationIntent.putExtras(bundle);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
        notification.setLatestEventInfo(context, contentTitle, contentText,
                contentIntent);
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        //用mNotificationManager的notify方法通知用户生成标题栏消息通知
        mNotificationManager.notify(1, notification);
    }

    @Override
    public void onCreate() {
        finalDb = FinalDb.create(NewCompany.this);
        new Thread(runnable).start();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                getCompanyNew();
                upLoad();
            }
        };
        super.onCreate();
    }


    public IBinder onBind(Intent intent) {
        return new NewCompanyBinder();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        onDestroy();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }
}
